package com.example.chatgpt000.service.impl;

import com.example.chatgpt000.service.OpenAiService;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.common.Choice;
import com.unfbx.chatgpt.entity.completions.CompletionResponse;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Arrays;
import java.util.List;

@Service
public class OpenAiServiceImpl implements OpenAiService {

    @Override
    public List getAnswer(String question) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
        //日志输出可以不添加
        //HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        //httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OpenAiClient openAiClient = OpenAiClient.builder()
                .apiKey("")
                .connectTimeout(50)
                .writeTimeout(50)
                .readTimeout(50)
                .proxy(proxy)
                //.interceptor(Collections.singletonList(httpLoggingInterceptor))
                .apiHost("https://api.openai.com/")
                .build();
        CompletionResponse completions = openAiClient.completions(question);
        List<Choice> choices = Arrays.stream(completions.getChoices()).toList();
        return choices;
    }
}

